<template>
  <div class="employee-manage">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>员工管理</h2>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" inline>
        <el-form-item label="员工姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入员工姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="员工账号">
          <el-input
            v-model="searchForm.account"
            placeholder="请输入员工账号"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch" :loading="loading">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          <el-button type="success" :icon="Plus" @click="handleAdd">新增员工</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="employeeList"
          stripe
          border
          style="width: 100%"
          :height="tableHeight"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          
          <el-table-column prop="avatar" label="头像" width="80" align="center">
            <template #default="{ row }">
              <el-avatar
                :src="row.avatar"
                :size="40"
                :icon="UserFilled"
                class="employee-avatar"
              />
            </template>
          </el-table-column>

          <el-table-column prop="name" label="员工姓名" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="employee-name">
                <el-text class="name-text" type="primary">{{ row.name }}</el-text>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="account" label="员工账号" min-width="120" show-overflow-tooltip />

          <el-table-column prop="phone" label="手机号" width="130" align="center" />

          <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />

          <el-table-column prop="gender" label="性别" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.gender === 1 ? 'primary' : 'danger'" size="small">
                {{ row.gender === 1 ? '男' : '女' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="180" align="center">
            <template #default="{ row }">
              <div class="time-display">
                <span class="relative-time" :title="formatDateTime(row.createTime)">
                  {{ formatRelativeTime(row.createTime) }}
                </span>
                <div class="exact-time">{{ formatDateTime(row.createTime) }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="updateTime" label="修改时间" width="180" align="center">
            <template #default="{ row }">
              <div class="time-display">
                <span class="relative-time" :title="formatDateTime(row.updateTime)">
                  {{ formatRelativeTime(row.updateTime) }}
                </span>
                <div class="exact-time">{{ formatDateTime(row.updateTime) }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="{ row }">
              <div class="operation-buttons">
                <el-button type="warning" size="small" :icon="Edit" @click="handleEdit(row)">
                  编辑
                </el-button>
                <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[5, 10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>


    <!-- 新增/编辑员工对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑员工' : '新增员工'"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="employeeFormRef"
        :model="employeeForm"
        :rules="employeeRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="name">
              <el-input v-model="employeeForm.name" placeholder="请输入员工姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工账号" prop="account">
              <el-input v-model="employeeForm.account" placeholder="请输入员工账号" :disabled="isEdit" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="employeeForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="employeeForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="employeeForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password" v-if="!isEdit">
              <el-input
                v-model="employeeForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="头像" prop="avatar">
          <div class="avatar-upload-container">
            <!-- 头像上传组件 -->
            <el-upload
              class="avatar-uploader"
              :action="''"
              :http-request="handleAvatarUpload"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              accept="image/*"
            >
              <div v-if="employeeForm.avatar" class="avatar-preview">
                <el-avatar :src="employeeForm.avatar" :size="80" />
                <div class="avatar-overlay">
                  <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    circle
                    @click.stop="removeAvatar"
                  />
                </div>
              </div>
              <div v-else class="avatar-placeholder">
                <el-icon class="avatar-uploader-icon" v-if="!uploadLoading">
                  <Plus />
                </el-icon>
                <el-icon class="avatar-uploader-icon is-loading" v-else>
                  <Loading />
                </el-icon>
                <div class="upload-text">{{ uploadLoading ? '上传中...' : '点击上传头像' }}</div>
              </div>
            </el-upload>
            
            <!-- 手动输入URL选项 -->
            <div class="url-input-section">
              <el-input
                v-model="employeeForm.avatar"
                placeholder="或直接输入头像URL"
                clearable
              >
                <template #prepend>头像URL</template>
              </el-input>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete,
  UserFilled,
  Loading
} from '@element-plus/icons-vue'
import { queryEmployeeList, findEmployee, addEmployee, updateEmployee, deleteEmployee, uploadImage } from '@/api/school'

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const uploadLoading = ref(false)
const employeeList = ref([])
const editDialogVisible = ref(false)
const isEdit = ref(false)
const employeeFormRef = ref()

// 表格高度计算
const tableHeight = computed(() => {
  return 'calc(100vh - 320px)'
})

// 搜索表单
const searchForm = reactive({
  name: '',
  account: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  limit: 5,
  total: 0
})

// 员工表单
const employeeForm = reactive({
  id: null,
  name: '',
  account: '',
  phone: '',
  email: '',
  gender: null,
  avatar: '',
  password: ''
})

// 表单验证规则
const employeeRules = {
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' }
  ],
  account: [
    { required: true, message: '请输入员工账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度应为3-20个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 获取员工列表
const getEmployeeList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      name: searchForm.name || undefined,
      account: searchForm.account || undefined
    }
    
    const response = await queryEmployeeList(params)
    if (response && response.code === 0) {
      employeeList.value = response.data || []
      pagination.total = response.count || 0
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getEmployeeList()
}

// 重置搜索
const handleReset = () => {
  searchForm.name = ''
  searchForm.account = ''
  pagination.page = 1
  getEmployeeList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.limit = size
  pagination.page = 1
  getEmployeeList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  getEmployeeList()
}

// 新增员工
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  editDialogVisible.value = true
}

// 编辑员工
const handleEdit = async (row) => {
  try {
    const response = await findEmployee(row.id)
    if (response && response.code === 0) {
      isEdit.value = true
      // 直接使用后端返回的数据，现在VO中包含了id字段
      Object.assign(employeeForm, {
        ...response.data,
        password: '' // 编辑时不显示密码
      })
      editDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取员工信息失败:', error)
    ElMessage.error('获取员工信息失败')
  }
}

// 删除员工
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除员工"${row.name}"吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteEmployee(row.id)
      if (response && response.code === 0) {
        ElMessage.success('删除成功')
        getEmployeeList()
      }
    } catch (error) {
      console.error('删除员工失败:', error)
      ElMessage.error('删除员工失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 保存员工
const handleSave = () => {
  employeeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        saveLoading.value = true
        const formData = { ...employeeForm }
        
        // 新增时删除ID字段，编辑时保留ID字段
        if (!isEdit.value) {
          delete formData.id
        }

        let response
        if (isEdit.value) {
          response = await updateEmployee(formData)
        } else {
          response = await addEmployee(formData)
        }

        if (response && response.code === 0) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          editDialogVisible.value = false
          getEmployeeList()
        }
      } catch (error) {
        console.error('保存员工失败:', error)
        ElMessage.error('保存员工失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义头像上传处理
const handleAvatarUpload = async (options) => {
  const { file } = options
  
  try {
    uploadLoading.value = true
    const response = await uploadImage(file)
    
    if (response && response.code === 0) {
      employeeForm.avatar = response.data
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error(response?.msg || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  } finally {
    uploadLoading.value = false
  }
}

// 移除头像
const removeAvatar = () => {
  employeeForm.avatar = ''
}

// 重置表单
const resetForm = () => {
  Object.assign(employeeForm, {
    id: null,
    name: '',
    account: '',
    phone: '',
    email: '',
    gender: null,
    avatar: '',
    password: ''
  })
  if (employeeFormRef.value) {
    employeeFormRef.value.resetFields()
  }
}

// 格式化日期时间显示
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  
  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) return dateTimeStr
    
    const now = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    
    // 如果是今年，不显示年份
    if (year === now.getFullYear()) {
      return `${month}-${day} ${hours}:${minutes}`
    }
    
    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('时间格式化错误:', error)
    return dateTimeStr
  }
}

// 格式化相对时间显示
const formatRelativeTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  
  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) return dateTimeStr
    
    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffSeconds = Math.floor(diffMs / 1000)
    const diffMinutes = Math.floor(diffSeconds / 60)
    const diffHours = Math.floor(diffMinutes / 60)
    
    // 未来时间显示为具体时间
    if (diffMs < 0) {
      return '未来时间'
    }
    
    // 今天的时间
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const dateOnly = new Date(date)
    dateOnly.setHours(0, 0, 0, 0)
    const daysDiff = Math.floor((today.getTime() - dateOnly.getTime()) / (1000 * 60 * 60 * 24))
    
    // 相对时间显示
    if (daysDiff === 0) {
      // 今天
      if (diffSeconds < 60) {
        return '刚刚'
      } else if (diffMinutes < 60) {
        return `${diffMinutes}分钟前`
      } else {
        return `${diffHours}小时前`
      }
    } else if (daysDiff === 1) {
      return '昨天'
    } else if (daysDiff === 2) {
      return '前天'
    } else if (daysDiff < 7) {
      return `${daysDiff}天前`
    } else if (daysDiff < 30) {
      const weeks = Math.floor(daysDiff / 7)
      return `${weeks}周前`
    } else if (daysDiff < 365) {
      const months = Math.floor(daysDiff / 30)
      return `${months}个月前`
    } else {
      const years = Math.floor(daysDiff / 365)
      return `${years}年前`
    }
  } catch (error) {
    console.error('相对时间格式化错误:', error)
    return formatDateTime(dateTimeStr)
  }
}

// 页面加载时获取数据
onMounted(() => {
  getEmployeeList()
})
</script>

<style scoped>
.employee-manage {
  padding: 5px 20px 5px 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  
  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

/* Webkit浏览器滚动条样式 */
.employee-manage::-webkit-scrollbar {
  width: 8px;
}

.employee-manage::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.employee-manage::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.employee-manage::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

.page-header {
  margin-bottom: 8px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.search-card {
  margin-bottom: 8px;
}

.table-card {
  background-color: #fff;
  margin-bottom: 10px;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.table-wrapper {
  flex: 1;
  overflow: hidden;
}

.employee-avatar {
  border: 2px solid #e4e7ed;
  transition: border-color 0.3s;
}

.employee-avatar:hover {
  border-color: #409eff;
}

.employee-name {
  display: flex;
  flex-direction: column;
}

.name-text {
  font-weight: 600;
  margin-bottom: 4px;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

:deep(.operation-buttons .el-button) {
  margin: 0 !important;
  min-width: 70px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  border-radius: 6px;
  font-weight: 500;
}

:deep(.operation-buttons .el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.operation-buttons .el-button:active) {
  transform: translateY(0);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 10px 20px;
  flex-shrink: 0;
  background-color: #fff;
}


.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 时间显示样式 */
.time-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.relative-time {
  font-weight: 500;
  color: #409eff;
  font-size: 13px;
  cursor: help;
}

.exact-time {
  font-size: 11px;
  color: #909399;
  line-height: 1.2;
}

/* 头像上传样式 */
.avatar-upload-container {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 80px;
  height: 80px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #fafafa;
}

.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  margin-bottom: 4px;
}

.avatar-uploader-icon.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.upload-text {
  color: #606266;
  font-size: 12px;
  text-align: center;
}

.avatar-preview {
  position: relative;
  width: 100%;
  height: 100%;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 0 6px 0 6px;
  padding: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-preview:hover .avatar-overlay {
  opacity: 1;
}

.url-input-section {
  flex: 1;
  display: flex;
  align-items: center;
}

/* 响应式优化 */
@media screen and (max-width: 768px) {
  .employee-manage {
    padding: 5px 15px 5px 15px;
    max-height: calc(100vh - 50px);
  }
  
  .pagination-container {
    justify-content: center;
    margin-bottom: 8px;
    padding: 10px 15px;
  }
  
  
  .time-display {
    gap: 1px;
  }
  
  .relative-time {
    font-size: 12px;
  }
  
  .exact-time {
    font-size: 10px;
  }
  
  .avatar-upload-container {
    flex-direction: column;
    gap: 15px;
  }
  
  /* 移动端操作按钮优化 */
  .operation-buttons {
    flex-direction: column;
    gap: 6px;
  }
  
  :deep(.operation-buttons .el-button) {
    min-width: 60px !important;
    height: 28px !important;
    font-size: 12px !important;
  }
}
</style>
